// 定时任务，删除一天前的记录、图片
const schedule = require('node-schedule');
const path = require('path');
const fs = require('fs');
const strangerRecordModel = require('../models/record_stranger.model');
const studentRecordModel = require('../models/record_student.model');
const zeroTimeStamp = new Date().setHours(0,0,0,0);
const timeStamp = zeroTimeStamp - 1000*60*60*24*1; // 一天前
const bUtils = require('../common/businessUtils')

function deleteFolder(path) {
    let files = [];
    if (fs.existsSync(path)) {
      if (fs.statSync(path).isDirectory()) {
        files = fs.readdirSync(path);
        files.forEach(function (file, index) {
            const picStamp = Number(file.slice(0,13))
            if(picStamp<timeStamp){
                const curPath = path + "/" + file;
                if (fs.statSync(curPath).isDirectory()) {
                    deleteFolder(curPath);
                } else {
                    fs.unlinkSync(curPath);
                }
            }
        })
      } 
    }
}
module.exports = function(){
    schedule.scheduleJob('0 0 2 * * *', async function(){
        try{
            // 删除记录
            await studentRecordModel.remove({
                c_time:{
                    $lt:timeStamp/1000
                }
            })
            await strangerRecordModel.remove({
                r_at:{
                    $lt:new Date(timeStamp)
                }
            })
            // 删除抓拍图片
            deleteFolder(path.resolve(__dirname,'../../res/julong_record'))

            // 清空考勤表
            bUtils.clearAttendanceList()

            // 清空学生信息表       
            // bUtils.clearStudentInfo()

            // 清空设备底库
            bUtils.emptyAllDeviceLibrary()
        }catch(err){
            console.log(err)
        }
    })

    
    // schedule.scheduleJob('0 * * * * *', bUtils.getNextDayClass)

    // 考勤统计轮训
    const attendanceInterval = 1000*60*5 //五分钟间隔
    global.setInterval(()=>{
            bUtils.sendAttendanceInfo()
        },
        attendanceInterval
    )
}